package com.my.gis.config.jts.converter;

import com.my.gis.config.jts.jts.JtsGeometry;
import net.postgis.jdbc.PGgeometry;
import org.locationtech.jts.geom.Geometry;

import java.sql.SQLException;

/**
 * Converter JTS Geometry to/from byte array.
 * Inspired by
 * <a
 * href="http://www.dev-garden.org/2011/11/27/loading-mysql-spatial-data-with-jdbc-and-jts-wkbreader/">Loading
 * MySQL Spatial Data with JDBC and JTS WKBReader</a>. Using Object instead
 * of byte[] because of codegen.
 *
 * @ClassName GeometryConverter
 * @Date 2022-04-15 0:32
 * @Version 1.0
 */
public class PgGeometryConverter extends GeometryConverter {

    /**
     * Convert byte array containing SRID + WKB Geometry into Geometry object
     */
    @Override
    public Geometry from(Object databaseObject) throws SQLException {
        final PGgeometry pGgeometry = (PGgeometry) databaseObject;
        if (pGgeometry == null) {
            return null;
        }
        String value = pGgeometry.getValue();
        // Read Geometry
        JtsGeometry jtsGeometry = new JtsGeometry(value);
        return jtsGeometry.getGeometry();
    }

    /**
     * Convert Geometry object into byte array containing SRID + WKB Geometry
     */
    @Override
    public Object to(Geometry geometry) throws SQLException {
        if (geometry == null) {
            return null;
        }

        PGgeometry pGeometry = new PGgeometry();
        pGeometry.setValue(geometry.toText()); //获取空间WKT字符串转PGgeometry.claas 包装写入数据库
        return pGeometry;
    }

    @Override
    public Class fromType() {
        return PGgeometry.class;
    }

    @Override
    public Class<Geometry> toType() {
        return Geometry.class;
    }

    @Override
    public String getDatabaseProductName() {
        return "PostgreSQL";
    }
}
